package javaUnit;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


public class oFile {

	/**
	 * 递归删除 删除某个目录及目录下的所有子目录和文件
	 * 
	 * @param file 文件或目录
	 * @return 删除结果
	 */
	public static boolean delFiles(File file) {
		boolean result = false;
		// 目录
		if (file.isDirectory()) {
			File[] childrenFiles = file.listFiles();
			for (File childFile : childrenFiles) {
				result = delFiles(childFile);
				if (!result) {
					return result;
				}
			}
		}
		// 删除 文件、空目录
		result = file.delete();
		return result;
	}

	/**
	 * 删除文件
	 * 
	 * @param fileName
	 * @return
	 */

	public static boolean delete(String fileName) {
		try {
			File sourceFile = new File(fileName);
			if (sourceFile.isDirectory()) {
				for (File listFile : sourceFile.listFiles()) {
					delete(listFile.getAbsolutePath());
				}
			}
			return sourceFile.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 如果目录不存在，就创建文件
	 * 
	 * @param dirPath
	 * @return
	 */
	public static String mkdirs(String dirPath) {
		try {
			File file = new File(dirPath);
			if (!file.exists()) {
				file.mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dirPath;
	}

	/* 判断文件是否存在 */
	public static boolean isExists(String filePath) {
		File file = new File(filePath);
		return file.exists();
	}

	/* 判断是否是文件夹 */
	public static boolean isDir(String path) {
		File file = new File(path);
		if (file.exists()) {
			return file.isDirectory();
		} else {
			return false;
		}
	}

	/**
	 * 文件或者目录重命名
	 * 
	 * @param oldFilePath 旧文件路径
	 * @param newName     新的文件名,可以是单个文件名和绝对路径
	 * @return
	 */
	public static boolean renameTo(String oldFilePath, String newName) {
		try {
			File oldFile = new File(oldFilePath);
			// 若文件存在
			if (oldFile.exists()) {
				// 判断是全路径还是文件名
				if (newName.indexOf("/") < 0 && newName.indexOf("\\") < 0) {
					// 单文件名，判断是windows还是Linux系统
					String absolutePath = oldFile.getAbsolutePath();
					if (newName.indexOf("/") > 0) {
						// Linux系统
						newName = absolutePath.substring(0, absolutePath.lastIndexOf("/") + 1) + newName;
					} else {
						newName = absolutePath.substring(0, absolutePath.lastIndexOf("\\") + 1) + newName;
					}
				}
				File file = new File(newName);
				// 判断重命名后的文件是否存在
				if (file.exists()) {
					System.out.println("该文件已存在,不能重命名");
				} else {
					// 不存在，重命名
					return oldFile.renameTo(file);
				}
			} else {
				System.out.println("原该文件不存在,不能重命名");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/* 文件拷贝操作 */
	public static void copy(String sourceFile, String targetFile) {
		File source = new File(sourceFile);
		File target = new File(targetFile);
		target.getParentFile().mkdirs();
		FileInputStream fis = null;
		FileOutputStream fos = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fis = new FileInputStream(source);
			fos = new FileOutputStream(target);
			in = fis.getChannel();// 得到对应的文件通道
			out = fos.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (fos != null) {
					fos.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/* 写入Text文件操作 */
	public static void writeText(String filePath, String content, boolean isAppend) {
		FileOutputStream outputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			outputStream = new FileOutputStream(filePath, isAppend);
			outputStreamWriter = new OutputStreamWriter(outputStream);
			bufferedWriter = new BufferedWriter(outputStreamWriter);
			bufferedWriter.write(content);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedWriter != null) {
					bufferedWriter.close();
				}
				if (outputStreamWriter != null) {
					outputStreamWriter.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/* 读取Text文件操作 */
	public static String readText(String filePath) {
		String lines = "";
		try {
			FileReader fileReader = new FileReader(filePath);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				lines += line + "\n";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lines;
	}

	/**
     * 下载url的文件到指定文件路径里面,如果文件父文件夹不存在则自动创建
     * url 下载的http地址
     * path 文件存储地址
     * return 如果文件大小大于2k则返回true
     */
    public static boolean downloadCreateDir(String url,String path){
        HttpURLConnection connection=null;
        InputStream in = null;
        FileOutputStream o=null;
        try{
            URL httpUrl=new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Charset", "gbk");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestMethod("GET");
            
            byte[] data=new byte[1024];
            File f=new File(path);
            File parentDir = f.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            if(connection.getResponseCode() == 200){
                in = connection.getInputStream();
                o=new FileOutputStream(path);
                int n=0;
                while((n=in.read(data))>0){
                    o.write(data, 0, n);
                    o.flush();
                }
            }
            if(f.length()>2048){  //代表文件大小
                return true;  //如果文件大于2k则返回true
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            try{
                if(in != null){
                    in.close();
                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
            try{o.close();}catch(Exception ex){}
            try{connection.disconnect();}catch(Exception ex){}
        }
        return false;
    }

    /**
     * 解压Zip文件
     * @param path zip文件目录
     */
    public static void unZip(String path) {
        int count = -1;
        String savepath = "";

        File file = null;
        InputStream is = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        savepath = path.substring(0, path.lastIndexOf(".")) + File.separator; // 保存解压文件目录
        new File(savepath).mkdir(); // 创建保存目录
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(path,Charset.forName("GBK")); // 解决中文乱码问题
            Enumeration<?> entries = zipFile.entries();  //枚举ZIP中的所有文件

            while (entries.hasMoreElements()) {
                byte buf[] = new byte[2048];

                ZipEntry entry = (ZipEntry) entries.nextElement();

                String filename = entry.getName();  //获取文件名
                filename = savepath + filename;
                boolean ismkdir = false;
                if (filename.lastIndexOf("/") != -1) { // 检查此文件是否带有文件夹
                    ismkdir = true;
                }

                if (entry.isDirectory()) { // 如果此枚举文件是文件夹则创建,并且遍历下一个
                    file = new File(filename);
                    file.mkdirs();
                    continue;
                }
                file = new File(filename);  //此枚举文件不是目录
                if (!file.exists()) {  //如果文件不存在并且文件带有目录
                    if (ismkdir) {
                        new File(filename.substring(0, filename
                                .lastIndexOf("/"))).mkdirs(); // 先创建目录
                    }
                }
                file.createNewFile(); //再创建文件

                is = zipFile.getInputStream(entry);
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos, 2048);

                while ((count = is.read(buf)) > -1) {
                    bos.write(buf, 0, count);
                }
                bos.flush();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (zipFile != null) {
                    zipFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    /**
     * 把GBK文件转为UTF-8
     * 两个参数值可以为同一个路径
     * @param srcFileName 源文件
     * @param destFileName 目标文件
     * @throws IOException
     */
    private static void transferFile(String srcFileName, String destFileName) throws IOException {
        String line_separator = System.getProperty("line.separator"); 
        FileInputStream fis = new FileInputStream(srcFileName);
        StringBuffer content = new StringBuffer();
        DataInputStream in = new DataInputStream(fis);
        BufferedReader d = new BufferedReader(new InputStreamReader(in, "GBK"));  //源文件的编码方式
        String line = null;
        while ((line = d.readLine()) != null)
         content.append(line + line_separator);
        d.close();
        in.close();
        fis.close();
            
        Writer ow = new OutputStreamWriter(new FileOutputStream(destFileName), "utf-8");  //需要转换的编码方式
        ow.write(content.toString());
        ow.close();
    }
}
